﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ViewCart : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if ( !IsPostBack )
        {
            LoadViewCart();
        }
    }
    public void LoadViewCart()
    {
        gvListCart.DataSource = HttpContext.Current.Session[ShoppingCartDTO.SessionListCart];
        gvListCart.DataBind();
    }
    protected void gvListCart_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if ( e.Row.RowType == DataControlRowType.Footer )
        {
            var shoppingCart = ShoppingCartDTO.GetShoppingCartCurrent(HttpContext.Current);
            e.Row.Cells[3].Text = "Total : " + shoppingCart.GetTotalMoney();
        }
    }
    protected void gvListCart_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "DeleteFormCart" )
        {
            var shoppingCart = ShoppingCartDTO.GetShoppingCartCurrent(HttpContext.Current);
            for(int i= 0 ; i< shoppingCart.ListCart.Count; i++) 
            {
                CheckBox cbxDelete = (CheckBox)gvListCart.Rows[i].FindControl("cbxDelete");
                if ( cbxDelete.Checked)
                {
                    int iAlbumID = int.Parse(gvListCart.DataKeys[i].Value.ToString());
                    bool bCheck = shoppingCart.RemoveFromCart(iAlbumID);
                    if (bCheck)
                    {
                        Response.Redirect("~/ViewCart.aspx");
                    }
                }
            } 
        }
    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        try
        {
            var shoppingCart = ShoppingCartDTO.GetShoppingCartCurrent(HttpContext.Current);
            foreach (GridViewRow row in gvListCart.Rows)
            {
                int iAlbumID = int.Parse(gvListCart.DataKeys[row.RowIndex].Value.ToString());
                TextBox txtCount = new TextBox();
                txtCount = (TextBox)row.Cells[1].FindControl("txtCount");
                int iCount = int.Parse(txtCount.Text);
                bool bCheck = shoppingCart.UpdateCart(iAlbumID, iCount);
            }
            Response.Redirect("~/ViewCart.aspx");
            
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}